<template>
  <view class="home-content">
    <mescroll-uni :up="{ onScroll: true }" @down="handleRefresh" @up="handleLoadMore" @scroll="handleScroll">
      <view class="box">
        <CommonWaterfallFlow ref="waterfallFlowRef" :list="listData" />
      </view>
    </mescroll-uni>
  </view>
</template>
<script setup lang="ts">
import { HOME_LIST } from "@/api"
import CommonWaterfallFlow from "@/components/WaterfallFlow.vue"
import { onLoad, onUnload } from "@dcloudio/uni-app"
import MescrollUni from "mescroll-uni"
import { getCurrentInstance, reactive, ref, toRaw } from "vue"

/** data */
// 获取当前实例
const instance = getCurrentInstance()
// 监视器
const observer = uni.createIntersectionObserver(instance, { observeAll: true })
// 滚动计时器
const scrollTimer = ref<number>()
// 监视器计时器
const observerTimer = ref<number>()
// 提示组件
const waterfallFlowRef = ref<InstanceType<typeof CommonWaterfallFlow>>()
// 列表表单
const listForm = reactive<{
  pageNum: number
  pageSize: number
  total: number
  isRefresh: string | boolean
  isLoading: boolean
}>({
  pageNum: 1,
  pageSize: 20,
  total: 0,
  isRefresh: false,
  isLoading: false
})
// 列表数据
const listData = ref<any[]>([])

// 获取列表数据
const getListData = (page: number = 1, el?: any) => {
  if (page === 1) {
    listData.value = []
  }
  listForm.pageNum = page
  listForm.isLoading = true

  HOME_LIST(toRaw(listForm)).then((res: any) => {
    if (res.data) {
      if (page === 1) listForm.total = Number(res.data.total)
      if (res.data.list) listData.value = [...toRaw(listData.value), ...res.data.list]
    }

  }).finally(() => {
    listForm.isLoading = false
    listForm.isRefresh = false

    el?.endSuccess(listForm.pageSize * listForm.pageNum, listForm.pageSize * listForm.pageNum < listForm.total)
  })
}

// 下拉刷新
const handleRefresh = (mescroll: any) => {
  listForm.isRefresh = true
  getListData(1, mescroll)
}

const handleScroll = () => {
  waterfallFlowRef.value?.pause()

  clearTimeout(scrollTimer.value)
  scrollTimer.value = setTimeout(() => {
    let _data: any

    observer.disconnect()
    observer.relativeTo(".roll").observe(".video", (res: any) => {
      if (res.intersectionRatio === 1 && res.id) {
        if (!_data || _data.intersectionRect.top > res.intersectionRect.top) {
          _data = res
        }

        clearTimeout(observerTimer.value)
        observerTimer.value = setTimeout(() => {
          waterfallFlowRef.value?.play(_data.id)
        }, 200)
      }
    })
  }, 200)
}

// 加载更多
const handleLoadMore = (mescroll: any) => {
  if (listForm.pageNum < Math.ceil(listForm.total / listForm.pageSize) && !listForm.isLoading) {
    getListData(listForm.pageNum + 1, mescroll)
  }
}

onLoad((option: any) => {
  listForm.total = Number(option.total) || 0

  getListData()
})

onUnload(() => {
  observer.disconnect()
})
</script>
<style lang="scss" scoped>
@use "@/styles/module/home.scss" as *;
</style>